package com.mall.module.product.controller;

import com.github.pagehelper.PageInfo;
import com.mall.common.result.Result;
import com.mall.common.util.SecurityUtils;
import com.mall.module.product.converter.ProductConverter;
import com.mall.module.product.domain.dto.BatchOperationDTO;
import com.mall.module.product.domain.dto.ProductCreateDTO;
import com.mall.module.product.domain.dto.ProductMarketingDTO;
import com.mall.module.product.domain.dto.ProductSkuDTO;
import com.mall.module.product.domain.dto.ProductSpuDTO;
import com.mall.module.product.domain.dto.ProductSpuPageQueryDTO;
import com.mall.module.product.domain.entity.ProductSpu;
import com.mall.module.product.domain.vo.NewProductVO;
import com.mall.module.product.domain.vo.ProductSpuDetailVO;
import com.mall.module.product.domain.vo.ProductSpuVO;
import com.mall.module.product.exception.ProductBusinessException;
import com.mall.module.product.service.ProductCategoryService;
import com.mall.module.product.service.ProductSpuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品SPU控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/product")
@Api(tags = "商品SPU管理")
public class ProductSpuController {

    private final ProductSpuService productSpuService;
    private final ProductConverter productConverter;
    private final ProductCategoryService productCategoryService;

    public ProductSpuController(ProductSpuService productSpuService,
                                ProductConverter productConverter,
                                ProductCategoryService productCategoryService) {
        this.productSpuService = productSpuService;
        this.productConverter = productConverter;
        this.productCategoryService = productCategoryService;
    }


    @PostMapping
    @ApiOperation("新增商品")
    public Result<Long> add(@RequestBody Object requestObj) {
        try {
            // 参数校验
            if (requestObj == null) {
                return Result.error(401, "请求数据不能为空");
            }
            ProductCreateDTO request;
            // 检查请求格式
            if (requestObj instanceof ProductCreateDTO) {
                // 标准格式，直接使用
                request = (ProductCreateDTO) requestObj;
                if (request.getSpuInfo() == null) {
                    return Result.error(401, "请求格式不正确，商品基本信息不能为空");
                }
            } else if (requestObj instanceof Map) {
                Map<String, Object> requestData = (Map<String, Object>) requestObj;
                log.info("接收到旧格式的商品创建请求，尝试转换");

                request = convertToProductCreateDTO(requestData);
            } else {
                return Result.error(401, "不支持的请求格式");
            }
            
            // 记录操作日志
            log.info("新增商品: {}, SKU数量: {}", request.getSpuInfo().getName(),
                request.getSkuList() != null ? request.getSkuList().size() : 0);
            
            // 1. 验证分类是否存在
            Long categoryId = request.getSpuInfo().getCategoryId();
            if (categoryId == null) {
                return Result.error(401, "商品分类ID不能为空");
            }
            
            try {
                productCategoryService.getDetail(categoryId);
            } catch (Exception e) {
                log.error("商品分类不存在: {}", categoryId, e);
                return Result.error(401, "商品分类不存在");
            }
            
            // 2. 转换DTO（包含XSS过滤和业务校验）
            ProductCreateDTO dto = productConverter.toCreateDto(request);
            
            // 3. 补充系统字段
            Long currentUserId;
            try {
                currentUserId = SecurityUtils.getCurrentUserId();
            } catch (Exception e) {
                log.warn("获取当前用户ID失败，使用默认用户ID", e);
                currentUserId = 1L; // 使用默认用户ID
            }
            
            dto.setCreateUser(currentUserId);
            dto.setCreateTime(LocalDateTime.now());
            
            // 4. 调用服务
            Long id = productSpuService.save(dto);
            
            // 5. 返回结果
            log.info("商品创建成功: ID={}", id);
            return Result.success(id, "商品新增成功");
        } catch (Exception e) {
            log.error("商品创建失败: {}", e.getMessage(), e);
            return Result.error(401, "商品创建失败: " + e.getMessage());
        }
    }


    /**
     * 更新商品信息
     */
    @PutMapping("/{id}")
    @ApiOperation("更新商品")
    public Result<Void> updateProductSpu(@PathVariable Long id, @Valid @RequestBody ProductSpuDTO dto) {
        dto.setId(id);
        productSpuService.update(dto);
        return Result.success();
    }

    /**
     * 获取商品详情
     */
    @GetMapping("/{id}")
    @ApiOperation("获取商品详情")
    public Result<ProductSpuDetailVO> getProductDetail(@PathVariable Long id) {
        ProductSpuDetailVO detail = productSpuService.getDetail(id);
        return Result.success(detail);
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除商品")
    public Result<Void> deleteProductSpu(@PathVariable Long id, @RequestParam(required = false) Long operatorId) {
        productSpuService.delete(id, operatorId);
        return Result.success();
    }

    /**
     * 分页查询商品列表
     */
    @GetMapping("/page")
    @ApiOperation("分页查询商品列表")
    public Result<PageInfo<ProductSpuVO>> pageProductSpu(ProductSpuPageQueryDTO queryDTO) {
        List<ProductSpuVO> list = productSpuService.page(queryDTO);
        PageInfo<ProductSpuVO> pageInfo = new PageInfo<>(list);
        return Result.success(pageInfo);
    }

    /**
     * 获取商品列表
     */
    @GetMapping("/list")
    @ApiOperation("获取商品列表")
    public Result<List<ProductSpuVO>> listProductSpu(ProductSpu condition) {
        List<ProductSpuVO> list = productSpuService.list(condition);
        return Result.success(list);
    }

    /**
     * 根据分类ID查询商品列表
     */
    @GetMapping("/category/{categoryId}")
    @ApiOperation("根据分类ID查询商品列表")
    public Result<List<ProductSpuVO>> listByCategory(@PathVariable Long categoryId) {
        List<ProductSpuVO> list = productSpuService.listByCategory(categoryId);
        return Result.success(list);
    }

    /**
     * 根据品牌ID查询商品列表
     */
    @GetMapping("/brand/{brandId}")
    @ApiOperation("根据品牌ID查询商品列表")
    public Result<List<ProductSpuVO>> listByBrand(@PathVariable Long brandId) {
        List<ProductSpuVO> list = productSpuService.listByBrand(brandId);
        return Result.success(list);
    }

    /**
     * 更新商品状态（上下架）
     */
    @PutMapping("/{id}/status")
    @ApiOperation("更新商品状态（上下架）")
    public Result<Void> updateProductStatus(@PathVariable Long id, @RequestParam Integer status) {
        productSpuService.updateStatus(id, status);
        return Result.success();
    }

    /**
     * 批量操作商品
     */
    @ApiOperation("批量操作商品")
    @PostMapping("/batch")
    public Result<Void> batchOperation(@Valid @RequestBody BatchOperationDTO operationDTO) {
        productSpuService.batchOperation(operationDTO);
        return Result.success();
    }

    /**
     * 关联商品标签
     */
    @ApiOperation("关联商品标签")
    @PostMapping("/{id}/tags")
    public Result<Void> addProductTags(@PathVariable Long id, @RequestBody List<Long> tagIds) {
        productSpuService.addProductTags(id, tagIds);
        return Result.success();
    }

    /**
     * 删除商品标签关联
     */
    @ApiOperation("删除商品标签关联")
    @DeleteMapping("/{id}/tags")
    public Result<Void> removeProductTags(@PathVariable Long id, @RequestBody List<Long> tagIds) {
        productSpuService.removeProductTags(id, tagIds);
        return Result.success();
    }

    /**
     * 关联商品促销
     */
    @ApiOperation("关联商品促销")
    @PostMapping("/{id}/promotions")
    public Result<Void> addProductPromotions(@PathVariable Long id, @RequestBody List<Long> promotionIds) {
        productSpuService.addProductPromotions(id, promotionIds);
        return Result.success();
    }

    /**
     * 删除商品促销关联
     */
    @ApiOperation("删除商品促销关联")
    @DeleteMapping("/{id}/promotions")
    public Result<Void> removeProductPromotions(@PathVariable Long id, @RequestBody List<Long> promotionIds) {
        productSpuService.removeProductPromotions(id, promotionIds);
        return Result.success();
    }

    /**
     * 新品专区接口实现
     */
    @GetMapping("/new")
    @ApiOperation("新品专区接口")
    public Result<PageInfo<NewProductVO>> listNewProduct(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize) {
        List<NewProductVO> list = productSpuService.listNewProduct(pageNum, pageSize);
        PageInfo<NewProductVO> pageInfo = new PageInfo<>(list);
        return Result.success(pageInfo);
    }

    /**
     * 新增商品（兼容旧格式，重定向到主端点）
     */
    @PostMapping("/add")
    @ApiOperation("新增商品（兼容旧格式）")
    public Result<Long> addProduct(@RequestBody Map<String, Object> requestData) {
        // 直接调用主端点
        return add(requestData);
    }

    /**
     * 将旧格式的请求数据转换为ProductCreateDTO对象
     */
    private ProductCreateDTO convertToProductCreateDTO(Map<String, Object> requestData) {
        // 创建ProductCreateDTO对象
        ProductCreateDTO createDTO = new ProductCreateDTO();
        
        // 创建并设置ProductSpuDTO
        ProductSpuDTO spuDTO = new ProductSpuDTO();
        spuDTO.setName((String) requestData.get("name"));
        
        // 处理可能是Integer类型的ID字段
        Object categoryIdObj = requestData.get("categoryId");
        if (categoryIdObj != null) {
            if (categoryIdObj instanceof Integer) {
                spuDTO.setCategoryId(((Integer) categoryIdObj).longValue());
            } else if (categoryIdObj instanceof Long) {
                spuDTO.setCategoryId((Long) categoryIdObj);
            } else if (categoryIdObj instanceof String) {
                try {
                    spuDTO.setCategoryId(Long.parseLong((String) categoryIdObj));
                } catch (NumberFormatException e) {
                    spuDTO.setCategoryId(null);
                }
            }
        }
        
        // 处理brandId
        Object brandIdObj = requestData.get("brandId");
        if (brandIdObj != null) {
            if (brandIdObj instanceof Integer) {
                spuDTO.setBrandId(((Integer) brandIdObj).longValue());
            } else if (brandIdObj instanceof Long) {
                spuDTO.setBrandId((Long) brandIdObj);
            } else if (brandIdObj instanceof String) {
                try {
                    spuDTO.setBrandId(Long.parseLong((String) brandIdObj));
                } catch (NumberFormatException e) {
                    spuDTO.setBrandId(null);
                }
            }
        }
        
        // 处理shippingTemplateId
        Object templateIdObj = requestData.get("shippingTemplateId");
        if (templateIdObj != null) {
            if (templateIdObj instanceof Integer) {
                spuDTO.setShippingTemplateId(((Integer) templateIdObj).longValue());
            } else if (templateIdObj instanceof Long) {
                spuDTO.setShippingTemplateId((Long) templateIdObj);
            } else if (templateIdObj instanceof String) {
                try {
                    spuDTO.setShippingTemplateId(Long.parseLong((String) templateIdObj));
                } catch (NumberFormatException e) {
                    spuDTO.setShippingTemplateId(null);
                }
            }
        }
        
        spuDTO.setMainImage((String) requestData.get("mainImage"));
        
        // 处理图册
        if (requestData.get("albumImages") instanceof List) {
            spuDTO.setAlbumImages((List<String>) requestData.get("albumImages"));
        }
        
        spuDTO.setVideo((String) requestData.get("video"));
        spuDTO.setDescription((String) requestData.get("description"));
        spuDTO.setDetail((String) requestData.get("detail"));
        
        // 处理状态
        if (requestData.get("status") instanceof Integer) {
            spuDTO.setStatus((Integer) requestData.get("status"));
        } else if (requestData.get("status") instanceof String) {
            try {
                spuDTO.setStatus(Integer.parseInt((String) requestData.get("status")));
            } catch (NumberFormatException e) {
                spuDTO.setStatus(0); // 默认下架
            }
        } else {
            spuDTO.setStatus(0); // 默认下架
        }
        
        // 设置SPU信息
        createDTO.setSpuInfo(spuDTO);
        
        // 处理SKU列表
        if (requestData.get("skuList") instanceof List) {
            List<Map<String, Object>> skuMapList = (List<Map<String, Object>>) requestData.get("skuList");
            List<ProductSkuDTO> skuDTOList = new ArrayList<>();
            
            for (Map<String, Object> skuMap : skuMapList) {
                ProductSkuDTO skuDTO = new ProductSkuDTO();
                skuDTO.setSkuCode((String) skuMap.get("skuCode"));
                skuDTO.setName((String) skuMap.get("name"));
                
                // 处理图片
                if (skuMap.get("images") instanceof List) {
                    skuDTO.setImages((List<String>) skuMap.get("images"));
                }
                
                // 处理价格
                skuDTO.setPrice(getBigDecimalValue(skuMap, "price"));
                skuDTO.setMarketPrice(getBigDecimalValue(skuMap, "marketPrice"));
                skuDTO.setCostPrice(getBigDecimalValue(skuMap, "costPrice"));
                
                // 处理库存
                skuDTO.setStock(getIntegerValue(skuMap, "stock"));
                skuDTO.setStockWarning(getIntegerValue(skuMap, "stockWarning", 10));
                
                // 处理其他字段
                skuDTO.setWeight(getBigDecimalValue(skuMap, "weight"));
                skuDTO.setVolume(getBigDecimalValue(skuMap, "volume"));
                skuDTO.setLimitPerOrder(getIntegerValue(skuMap, "limitPerOrder"));
                
                // 处理规格数据
                if (skuMap.get("specData") instanceof Map) {
                    skuDTO.setSpecData((Map<String, String>) skuMap.get("specData"));
                }
                
                // 处理预售配置
                if (skuMap.get("presellConfig") instanceof Map) {
                    Map<String, Object> presellMap = (Map<String, Object>) skuMap.get("presellConfig");
                    if (Boolean.TRUE.equals(presellMap.get("isPresell"))) {
                        ProductSkuDTO.PresellConfig presellConfig = new ProductSkuDTO.PresellConfig();
                        // 这里需要处理日期时间格式转换，简化处理
                        presellConfig.setDeliveryDays(getIntegerValue(presellMap, "deliveryDays"));
                        skuDTO.setPresellConfig(presellConfig);
                    }
                }
                
                skuDTOList.add(skuDTO);
            }
            
            createDTO.setSkuList(skuDTOList);
        } else {
            // 创建一个默认的SKU
            List<ProductSkuDTO> skuDTOList = new ArrayList<>();
            ProductSkuDTO defaultSku = new ProductSkuDTO();
            defaultSku.setName(spuDTO.getName());
            defaultSku.setPrice(new BigDecimal("0.01"));
            defaultSku.setStock(100);
            skuDTOList.add(defaultSku);
            createDTO.setSkuList(skuDTOList);
        }
        
        // 处理营销信息
        ProductMarketingDTO marketingDTO = new ProductMarketingDTO();
        
        // 处理标签ID列表，确保类型正确
        if (requestData.get("tagIds") instanceof List) {
            List<Object> tagIdObjs = (List<Object>) requestData.get("tagIds");
            List<Long> tagIds = new ArrayList<>();
            
            for (Object tagIdObj : tagIdObjs) {
                if (tagIdObj instanceof Integer) {
                    tagIds.add(((Integer) tagIdObj).longValue());
                } else if (tagIdObj instanceof Long) {
                    tagIds.add((Long) tagIdObj);
                } else if (tagIdObj instanceof String) {
                    try {
                        tagIds.add(Long.parseLong((String) tagIdObj));
                    } catch (NumberFormatException e) {
                        // 忽略无效值
                    }
                }
            }
            
            marketingDTO.setTagIds(tagIds);
        }
        
        // 处理促销ID列表，确保类型正确
        if (requestData.get("promotionIds") instanceof List) {
            List<Object> promotionIdObjs = (List<Object>) requestData.get("promotionIds");
            List<Long> promotionIds = new ArrayList<>();
            
            for (Object promotionIdObj : promotionIdObjs) {
                if (promotionIdObj instanceof Integer) {
                    promotionIds.add(((Integer) promotionIdObj).longValue());
                } else if (promotionIdObj instanceof Long) {
                    promotionIds.add((Long) promotionIdObj);
                } else if (promotionIdObj instanceof String) {
                    try {
                        promotionIds.add(Long.parseLong((String) promotionIdObj));
                    } catch (NumberFormatException e) {
                        // 忽略无效值
                    }
                }
            }
            
            marketingDTO.setPromotionIds(promotionIds);
        }
        
        // 处理是否新品
        if (requestData.get("isNew") instanceof Boolean) {
            marketingDTO.setIsNew((Boolean) requestData.get("isNew"));
        }
        
        // 处理是否推荐
        if (requestData.get("isRecommend") instanceof Boolean) {
            marketingDTO.setIsRecommend((Boolean) requestData.get("isRecommend"));
        }
        
        // 处理服务承诺
        if (requestData.get("services") instanceof List) {
            marketingDTO.setServices((List<String>) requestData.get("services"));
        }
        
        createDTO.setMarketingInfo(marketingDTO);
        
        return createDTO;
    }
    
    /**
     * 从Map中获取Integer类型的值
     */
    private Integer getIntegerValue(Map<String, Object> map, String key) {
        return getIntegerValue(map, key, null);
    }
    
    /**
     * 从Map中获取Integer类型的值，如果不存在则返回默认值
     */
    private Integer getIntegerValue(Map<String, Object> map, String key, Integer defaultValue) {
        Object value = map.get(key);
        if (value == null) {
            return defaultValue;
        }
        
        if (value instanceof Integer) {
            return (Integer) value;
        }
        
        if (value instanceof Long) {
            return ((Long) value).intValue();
        }
        
        if (value instanceof String) {
            try {
                return Integer.parseInt((String) value);
            } catch (NumberFormatException e) {
                return defaultValue;
            }
        }
        
        return defaultValue;
    }
    
    /**
     * 从Map中获取BigDecimal类型的值
     */
    private BigDecimal getBigDecimalValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
        
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        
        if (value instanceof Number) {
            return new BigDecimal(value.toString());
        }
        
        if (value instanceof String) {
            try {
                return new BigDecimal((String) value);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        
        return null;
    }
}
